package android.reasons;

import android.app.*;
import android.app.Mensaje;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.res.Configuration;
import android.entidades.Cronometro;
import android.entidades.Data;
import android.entidades.Usuario;
import android.entidades.Voz;
import android.facebook.FacebookApp;
import android.os.Bundle;
import android.support.v4.app.ActionBarDrawerToggle;
import android.support.v4.view.GravityCompat;
import android.support.v4.widget.DrawerLayout;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import android.service.reasons.ServicioReasons;


public class Wall extends Activity
{
    private CharSequence mTitle;
    private DrawerLayout mDrawerLayout;
    private ListView mDrawerList;
    private ActionBarDrawerToggle mDrawerToggle;
    private CharSequence mDrawerTitle;
    private String[] lstOpciones;
    private Fragment fragment;
    private FacebookApp face;
    
    private void selectItem(int position) 
     {
        
            switch(position)
            {
                case 0:
                    // update the main content by replacing fragments
                    fragment = new ViewFragment(); 
                    FragmentManager fragmentManager = getFragmentManager();
                    fragmentManager.beginTransaction().replace(R.id.content_frame, fragment).commit();
                    
                    // update selected item and title, then close the drawer
                    mDrawerList.setItemChecked(position, true);
                    mDrawerLayout.closeDrawer(mDrawerList);
                    break;
            }
    }
    
    /** Called when the activity is first created. */
    @Override 
    public void onCreate(Bundle savedInstanceState)
    {
        super.onCreate(savedInstanceState);
        ContextoAndroid.context = this;
        if(!isMyServiceRunning())
        {
            Intent i = new Intent(this, ServicioReasons.class);  
            i.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);  
            startService(i);
        }
        this.setContentView(R.layout.fragmentmain);
        startDrawerLayout(savedInstanceState);
        face = new FacebookApp(this);
    }
    
    private void startDrawerLayout(Bundle savedInstanceState) 
    {
        mTitle = mDrawerTitle = getTitle();
        lstOpciones = getResources().getStringArray(R.array.activities);
        mDrawerLayout = (DrawerLayout) findViewById(R.id.drawL);
        mDrawerLayout.setBackgroundResource(R.drawable.turquesa);
        mDrawerList = (ListView) findViewById(R.id.left_drawer);

        // set a custom shadow that overlays the main content when the drawer opens
        mDrawerLayout.setDrawerShadow(R.drawable.drawer_shadow, GravityCompat.START);
        // set up the drawer's list view with items and click listener
        mDrawerList.setAdapter(new ArrayAdapter<String>(this, R.layout.drawer_list_item, lstOpciones));
        mDrawerList.setOnItemClickListener(new DrawerItemClickListener());

        // enable ActionBar app icon to behave as action to toggle nav drawer
        getActionBar().setDisplayHomeAsUpEnabled(true);
        getActionBar().setHomeButtonEnabled(true);

        
        // ActionBarDrawerToggle ties together the the proper interactions
        // between the sliding drawer and the action bar app icon
        mDrawerToggle = new ActionBarDrawerToggle(
                this,                  /* host Activity */
                mDrawerLayout,         /* DrawerLayout object */
                R.drawable.ic_drawer,  /* nav drawer image to replace 'Up' caret */
                R.string.drawer_open,  /* "open drawer" description for accessibility */
                R.string.drawer_close  /* "close drawer" description for accessibility */
                ) {
            public void onDrawerClosed(View view) {
                getActionBar().setTitle(mTitle);
                invalidateOptionsMenu(); // creates call to onPrepareOptionsMenu()
            }

            public void onDrawerOpened(View drawerView) {
                getActionBar().setTitle(mDrawerTitle);
                invalidateOptionsMenu(); // creates call to onPrepareOptionsMenu()
            }
        };
        mDrawerLayout.setDrawerListener(mDrawerToggle);
        
        if(savedInstanceState== null)
            selectItem(0);

    }
    
     @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.menu, menu);
        return super.onCreateOptionsMenu(menu);
    }

    /* Called whenever we call invalidateOptionsMenu() */
    @Override
    public boolean onPrepareOptionsMenu(Menu menu) {
        // If the nav drawer is open, hide action items related to the content view
        //boolean drawerOpen = mDrawerLayout.isDrawerOpen(mDrawerList);
        //menu.findItem(R.id.menu_settings).setVisible(!drawerOpen);
        return super.onPrepareOptionsMenu(menu);
    }
    
    private class DrawerItemClickListener implements ListView.OnItemClickListener {
        @Override
        public void onItemClick(AdapterView<?> parent, View view, int position, long id) 
        {
            handleListView(position);
        }
    }
    
    private void handleListView(int index)
    {   
        Intent i = null;
        switch(index)
        {
            case 1:
                i = new Intent(this, Configuracion.class);
                startActivity(i);
                break;
            
            case 0:
                i = new Intent(this, Publicar.class);
                startActivity(i);
                break;
            case 2:
                i = new Intent(this, EditarPerfil.class);
                startActivity(i);
                break;
            case 3:
                new AlertDialog.Builder(this)
                    .setIcon(android.R.drawable.ic_dialog_alert)
                    .setTitle(R.string.quit)
                    .setMessage(R.string.really_quit)
                    .setPositiveButton(R.string.yes, new DialogInterface.OnClickListener() {

                        @Override
                        public void onClick(DialogInterface dialog, int which) {

                            //Stop the activity
                            if(Usuario.isUser().tipo == 1)
                            {
                                face.logoutFromFacebook();
                            }
                            Data.deleteID();
                            Cronometro.delete();
                            Usuario.deleteUser();
                            Voz.deleteVoz();
                            NotificationManager notificationManager = (NotificationManager)getSystemService(Context.NOTIFICATION_SERVICE);
                            notificationManager.cancelAll();
                            restartApp();
                        }

                    })
                    .setNegativeButton(R.string.no, null)
                    .show();
                break;
        }
    }
   
    private void restartApp()
    {
        Mensaje.Mostrar("Saliendo...");
        Intent i = new Intent(this,Inicio.class);
        startActivity(i);
    }   
    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
       // ActionBarDrawerToggle will take care of this.
        if (mDrawerToggle.onOptionsItemSelected(item)) 
        {
            return true;
        }
        // Handle action buttons
        switch(item.getItemId()) {
            
            default:
             return super.onOptionsItemSelected(item);
        }
        
    }
    
    @Override
    protected void onPostCreate(Bundle savedInstanceState) {
        super.onPostCreate(savedInstanceState);
        // Sync the toggle state after onRestoreInstanceState has occurred.
        mDrawerToggle.syncState();
    }

    @Override
    public void onConfigurationChanged(Configuration newConfig) {
        super.onConfigurationChanged(newConfig);
        // Pass any configuration change to the drawer toggls
        mDrawerToggle.onConfigurationChanged(newConfig);
    }
    
    private boolean isMyServiceRunning() 
    {
        ActivityManager manager = (ActivityManager) getSystemService(Context.ACTIVITY_SERVICE);
        for (ActivityManager.RunningServiceInfo service : manager.getRunningServices(Integer.MAX_VALUE)) {
            if (ServicioReasons.class.getName().equals(service.service.getClassName())) {
                return true;
            }
        }
        return false;
    }
    
}
